<?php
require_once('Init.php');
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

//static $str = '';
//function readedFile($str, $output = false) {
//    static $staticStr = '';
//    $staticStr .= $str;
//    if (($output)) {
//        return $staticStr;
//    }
//}

//$filename = "./readedFile.php";
//$handle = fopen($filename, "r");
//$contents = fread($handle, filesize($filename));
//fclose($handle);
//echo $contents;
$function = 'replaceFunctionInCode';
$at = Controller::getActionTemplate();
if (empty($_REQUEST['text'])) {
    $at->display(getDocumentRoot() . 'templates/saveFile.tpl');
    return 0;
} else {
    $wholeText = file_get_contents('./CodeToGui.php');
    $wholeTextWithSpace = str_replace(" ", "%20", $wholeText);
    ob_start();
    print_r('$wholeTextWithPlus = ');
    print_r($wholeTextWithSpace);
    print_r("\n");
    $text = ob_get_clean();
    error_log($text);
    file_put_contents('readFile.php', $wholeText);
    file_put_contents('./Code.php', $wholeTextWithSpace);
    $appendToFile = file_get_contents('appendToFile.txt');
    $wholeText .= $appendToFile;
//    echo $wholeText;
    file_put_contents('tplFile.php', $wholeText);
}


$fileStr = file('./tplFile.php', true);
$arr = $fileStr; //readedFile($fileStr, true);

$arrRows = array();
$checkDeniedArea = true;
foreach($arr as $key => $row) {
    if (false !== strpos($row, "function getFunctionName()")) {
        $checkDeniedArea =  strpos($row, "function getFunctionName()");
//        var_dump("muhhhhhh");
    }
    
//    if (false !== $checkDeniedArea) {
//    }
    if (false != $checkDeniedArea && 0 < preg_match("/[^*].*return /i", $row)) {
//        echo $row . "<br>";
//        $arrRegex = '';
//        $arrRegex = preg_replace('/(\$\w+)/', '<textarea cols="2">${1}</textarea>', $row);
        $arrRows[] = "handleArray(getFunctionName(), get_defined_vars());\n";
        
//        echo $arrRegex;
    }
    $arrRows[] = $row;
}
//var_dump($arrRows);
file_put_contents('savedFile.php', $arrRows);
function callSome() {
    require_once('./savedFile.php');
}
function error_handler($output)
{
    $error = error_get_last();
//    var_dump($error);
    $output = "";
//    foreach ($error as $info => $string) {
//        $output .= "{$info}: {$string}\n";
//    }
//        error_log("\n" . $output . "\n");
//    return $output;
}


//echo $text;
try {
    ob_start('error_handler');
    callSome();
    $text = ob_get_clean();
} catch(Exception $e) {
    echo '';
}

$storeVarArray = handleArray(false, false, true);
//var_dump($storeVarArray);
$len = count($storeVarArray[$function]);
$vars = $storeVarArray[$function][$len-1]['vars'];

///// Array Solution
//$arrOut = file('./readedFile.php', true);
//$fileOutStr  = file_get_contents('./readedFile.php');
//$fileOutStrReplaceN = str_replace("\n", "@", $fileOutStr);
//$arrManipulated = array();
//$functionFound = false;
//$openBracket = false;
//$closeBracket = false;

//foreach ($arrOut as $row) {
//    if (false !== strpos($row, 'function recursive')) {
//        $functionFound = true;
//    }
//    if ($functionFound && preg_match('/^{.*/', $row)) {
//        $openBracket = true;
//        var_dump("zong");
//    }
//    if ($openBracket && !$closeBracket) {
//        if (preg_match('/^}.*/', $row)) {
//            $closeBracket = true;
//            $functionFound = false;
//            var_dump("zing");
//        }
//        foreach ($vars as $name => $value) {
//            if (false !== strpos($row, $name . ' = ')) {
//                $cols = 2;
//                $rows = 1;
//                if (is_array($value)) {
//                    ob_start();
//                    print_r($value);
//                    $text = ob_get_clean();
//                    $value = $text;
//                    $cols = 20;
//                    $rows = 10;
//                }
//                $rowOut = '';
//                $rowOut = preg_replace('/(\$' . $name . ' =)/', '${1}<textarea cols="' . $cols . '" rows="' . $rows . '">' . $value . '</textarea>', $row);
//                $row = $rowOut;
//                var_dump($rowOut);
//            }
//        }
////        $arrRegex = '';
////        $outValue =
////        $arrRegex = preg_replace('/(\$\w+)/', '<textarea cols="2">vars${1}</textarea>', $row);
//    }
//    $arrManipulated[] = $row;
//}

//var_dump($arrManipulated);

//file_put_contents('manipulatedFile.txt', $arrManipulated);

////// String Solution
$fileOutStr  = file_get_contents('./readFile.php');
$fileOutStrN = '';
$fileOutStrReplaceN = str_replace(array("\n", " "), array("@", "%20"), $fileOutStr);
foreach ($vars as $name => $value) {
    $cols = 6;
    $rows = 1;
    $size = 0;
    if (is_array($value)) {
        ob_start();
        print_r($value);
        $text = ob_get_clean();
        $ausgabe = array();
        preg_match_all("/\n.*/", $text, $ausgabe, PREG_SET_ORDER);
        foreach ($ausgabe as $firstArray) {
            foreach ($firstArray as $textToCheckLen)
            if ($size <= strlen($textToCheckLen)) {
                $size = strlen($textToCheckLen);
            }
        }
        $value = str_replace("\n", "%2F", $text);
//        error_log("\n" . $size . "\n");
        $cols = (int)($size*1.5);
        if (110 < $cols) {
            $cols = 110;
        }
        $rows = 10;
    } elseif (is_string($value)) {
//        strlen($value);
        $cols = (int)(strlen($value)*1.5);
    }
    $rowOut = '';
    $rowOut = preg_replace('/(\$' . $name . '%20=)/', '${1}<textarea cols="' . $cols . '" rows="' . $rows . '">' . $value . '</textarea>', $row);
    $row = $rowOut;
//    var_dump($rowOut);
    $fileOutStrN = preg_replace('/(function%20' . $function . '.*)(\$' . $name . ')%20=%20/', '${1}${2} = <textarea cols="' . $cols . '" rows="' . $rows . '">' . $value . '</textarea>', $fileOutStrReplaceN);
    $fileOutStrReplaceN = $fileOutStrN;
}
$fileOutStr = str_replace(array("@"), array("\n"), $fileOutStrN);
ob_start();
print_r('$fileOutStr = ');
print_r($fileOutStr);
print_r("\n");
$text = ob_get_clean();
error_log($text);
//var_dump($fileOutStr);

file_put_contents('manipulatedFile.txt', $fileOutStr);

$myOutputString = file_get_contents('./manipulatedFile.txt');
//$replaceEscapeSpace = str_replace("%20", "&nbsp;", $myOutputString);
$nl2br = nl2br($myOutputString, false); //str_replace("%2F", "\n", nl2br($replaceEscapeSpace, false));

//$at->assign('manipulatedFunction', $nl2br);
//$at->display(getDocumentRoot() . 'templates/saveFile.tpl');
echo $nl2br; //nl2br($myOutputString, false);



//var_dump($storeVarArray);
